package com.moon.game.server;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.jboss.netty.channel.MessageEvent;

import com.google.protobuf.ByteString;
import com.moon.game.clazz.PBMessageProto.PBMessage;
import com.moon.game.command.ProfileMessage;
import com.moon.game.constants.App2ProfileConstants;
import com.moon.game.exception.GException;
import com.moon.game.service.ProfileService;

public class ProfileThread extends Thread{
	public static ProfileThread inst;
	private static final Logger log = Logger.getLogger(ProfileThread.class);
	private LinkedBlockingQueue<ProfileMessage> operaQueue = new LinkedBlockingQueue<ProfileMessage>();

	public synchronized static void init() throws GException {
		if (inst == null) {
			inst = new ProfileThread();
		}
	}

	public ProfileThread() {
	}

	/**
	 * 外部调用
	 */
	public void addRequest(ProfileMessage request) {
		if (operaQueue.size() > 200) {
			log.warn("login queue size:" + operaQueue.size());
		}
		operaQueue.add(request);
	}
	@Override
	public void run() {
		while (true) {
			ProfileMessage message = null;
			try {
				message = operaQueue.poll(100, TimeUnit.MILLISECONDS);
				while (message != null) {
					long start = System.currentTimeMillis();
					exe(message);
					long end = System.currentTimeMillis();
					if (end - start > 200) {
						log.warn("profile operation over:" + (end - start) + "second");
						log.info("operaQueue size:" + operaQueue.size());
					}
					message = operaQueue.poll();
				}
	        } catch (Exception e) {
	            log.error("player db error:", e);
	        }
		}
	}
	
	private void exe(ProfileMessage message) {
		PBMessage.Builder response = PBMessage.newBuilder();
		PBMessage.Builder request = message.getRequest().toBuilder();
		switch (request.getCmd()) {
			case App2ProfileConstants.CMD_ADD_PLAYER:// 创建player
				ProfileService.savePlayer2DB(request.getId(), request.getData());
				response.setData(request.getData());
				break;
			case App2ProfileConstants.CMD_UPDATE_PLAYER:// 更新player
				ProfileService.savePlayer2DB(request.getId(), request.getData());
				response.setData(request.getData());
				break;
			case App2ProfileConstants.CMD_GET_PLAYER:// 读取player
				ByteString d = ProfileService.getPlayerFromDB(request.getId());
				if (d != null) {
					response.setData(d);
				}
				break;
		}
		response.setCmd(request.getCmd());
		response.setStatus(request.getStatus());
		response.setId(request.getId());
		response.setSessionId(request.getSessionId());
		if (response.getIsReturn()) {
			resp(message.getEvent(),response);
		}
	}
	private void resp(MessageEvent event, PBMessage.Builder response){
		event.getChannel().write(response, event.getRemoteAddress());
	}
}
